<template>
  <div class="air-data-container">
    <div class="header">
      <h2>空气质量数据</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属家庭">
          <el-select 
            v-model="searchForm.family_id" 
            placeholder="请选择家庭"
            clearable
            @change="handleFamilyChange"
            @clear="handleFamilyClear"
            class="search-select"
          >
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检测地点">
          <el-select 
            v-model="searchForm.site_id" 
            placeholder="请选择检测地点"
            clearable
            @clear="handleSearch"
            :disabled="!searchForm.family_id"
            class="search-select"
          >
            <el-option
              v-for="item in filteredSiteList"
              :key="item.site_id"
              :label="getLocationName(item)"
              :value="item.site_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监测日期">
          <el-date-picker
            v-model="searchForm.recorded_at"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            @clear="handleSearch"
            class="search-date"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="airDataList" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="检测地点" min-width="180" align="center">
        <template #default="{ row }">
          {{ getLocationName(getSiteInfo(row.site_id)) }}
        </template>
      </el-table-column>
      <el-table-column label="PM2.5" align="center">
        <template #default="{ row }">
          <span :class="getAirQualityClass(row.pm25, 'pm25')">
            {{ row.pm25.toFixed(2) }} μg/m³
          </span>
        </template>
      </el-table-column>
      <el-table-column label="PM10" align="center">
        <template #default="{ row }">
          <span :class="getAirQualityClass(row.pm10, 'pm10')">
            {{ row.pm10.toFixed(2) }} μg/m³
          </span>
        </template>
      </el-table-column>
      <el-table-column label="温度" align="center">
        <template #default="{ row }">
          <span :class="getTemperatureClass(row.temperature)">
            {{ row.temperature.toFixed(1) }} °C
          </span>
        </template>
      </el-table-column>
      <el-table-column label="湿度" align="center">
        <template #default="{ row }">
          <span :class="getHumidityClass(row.humidity)">
            {{ row.humidity.toFixed(1) }} %
          </span>
        </template>
      </el-table-column>
      <el-table-column label="甲醛" align="center">
        <template #default="{ row }">
          <span :class="getFormaldehydeClass(row.formaldehyde)">
            {{ row.formaldehyde.toFixed(3) }} mg/m³
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="recorded_at" label="监测时间" width="180" align="center" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  getAirDataList,
  getAirDataBySiteId,
  getAirDataByTime,
  getAirDataByFamilyId
} from '@/api/airData'
import { getFamilyList } from '@/api/family'
import { getSiteList } from '@/api/site'
import { getRoomList } from '@/api/room'

// 数据列表
const airDataList = ref([])
const familyList = ref([])
const siteList = ref([])
const roomList = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  family_id: '',
  site_id: '',
  recorded_at: ''
})

// 根据选择的家庭过滤传感器列表
const filteredSiteList = computed(() => {
  if (!searchForm.value.family_id) return []
  return siteList.value.filter(site => {
    const room = roomList.value.find(room => room.room_id === site.room_id)
    return room && room.family_id === searchForm.value.family_id
  })
})

// 获取位置名称（家庭-房间-传感器）
const getLocationName = (site) => {
  if (!site) return '未知位置'
  const room = roomList.value.find(r => r.room_id === site.room_id)
  if (!room) return `未知房间-${site.site_name}`
  const family = familyList.value.find(f => f.family_id === room.family_id)
  if (!family) return `未知家庭-${room.room_name}-${site.site_name}`
  return `${family.family_name}-${room.room_name}-${site.site_name}`
}

// 获取传感器信息
const getSiteInfo = (siteId) => {
  return siteList.value.find(site => site.site_id === siteId)
}

// 家庭变更处理
const handleFamilyChange = () => {
  searchForm.value.site_id = '' // 清空传感器选择
  handleSearch()
}

// 家庭清空处理
const handleFamilyClear = () => {
  searchForm.value.family_id = ''
  searchForm.value.site_id = ''
  handleSearch()
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    let res

    if (searchForm.value.site_id) {
      res = await getAirDataBySiteId(searchForm.value.site_id)
    } else if (searchForm.value.recorded_at) {
      res = await getAirDataByTime(searchForm.value.recorded_at)
    } else if (searchForm.value.family_id) {
      res = await getAirDataByFamilyId(searchForm.value.family_id)
    } else {
      res = await getAirDataList()
    }

    airDataList.value = res.data
  } catch (error) {
    console.error('获取空气数据列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleSearch = () => {
  getList()
}

// 重置按钮点击
const handleReset = () => {
  searchForm.value = {
    family_id: '',
    site_id: '',
    recorded_at: ''
  }
  getList()
}

// 初始化数据
const initData = async () => {
  try {
    // 获取家庭列表
    const familyRes = await getFamilyList()
    familyList.value = familyRes.data
    
    // 获取房间列表
    const roomRes = await getRoomList()
    roomList.value = roomRes.data
    
    // 获取传感器列表
    const siteRes = await getSiteList()
    siteList.value = siteRes.data
    
    // 获取空气数据列表
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  initData()
})

// 添加空气质量评估方法
const getAirQualityClass = (value, type) => {
  if (type === 'pm25') {
    if (value <= 35) return 'quality-good'
    if (value <= 75) return 'quality-moderate'
    return 'quality-bad'
  }
  if (type === 'pm10') {
    if (value <= 50) return 'quality-good'
    if (value <= 150) return 'quality-moderate'
    return 'quality-bad'
  }
  return ''
}

const getTemperatureClass = (value) => {
  if (value < 16) return 'temp-cold'
  if (value > 28) return 'temp-hot'
  return 'temp-normal'
}

const getHumidityClass = (value) => {
  if (value < 30) return 'humidity-low'
  if (value > 70) return 'humidity-high'
  return 'humidity-normal'
}

const getFormaldehydeClass = (value) => {
  if (value <= 0.08) return 'quality-good'
  if (value <= 0.1) return 'quality-moderate'
  return 'quality-bad'
}
</script>

<style scoped>
.air-data-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 调整表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 统一下拉选择框和日期选择器宽度和样式 */
:deep(.search-select),
:deep(.search-date) {
  width: 200px;
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* 按钮组样式 */
.search-buttons {
  margin-left: auto;
}

/* 确保下拉选项文字可见 */
:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  color: #606266;
}

:deep(.el-select-dropdown__item.selected) {
  color: #409EFF;
  font-weight: 700;
}

/* 优化表单布局 */
:deep(.el-form--inline) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: flex-start;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 确保选择框内容完整显示 */
:deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}

/* 添加空气质量指标样式 */
.quality-good {
  color: #67C23A;
  font-weight: bold;
}

.quality-moderate {
  color: #E6A23C;
  font-weight: bold;
}

.quality-bad {
  color: #F56C6C;
  font-weight: bold;
}

.temp-cold {
  color: #409EFF;
  font-weight: bold;
}

.temp-normal {
  color: #67C23A;
  font-weight: bold;
}

.temp-hot {
  color: #F56C6C;
  font-weight: bold;
}

.humidity-low {
  color: #E6A23C;
  font-weight: bold;
}

.humidity-normal {
  color: #67C23A;
  font-weight: bold;
}

.humidity-high {
  color: #409EFF;
  font-weight: bold;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}
</style> 